package net.schmurgon.gwt.ui;

import com.google.gwt.app.place.AbstractRecordListActivity;
import com.google.gwt.app.place.PlaceController;
import com.google.gwt.app.place.RecordListView;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.requestfactory.shared.RecordListRequest;
import com.google.gwt.view.client.Range;
import net.schmurgon.gwt.request.RunnerRecord;
import net.schmurgon.gwt.shared.Gender;
import net.schmurgon.gwt.request.ApplicationRequestFactory;
import net.schmurgon.gwt.scaffold.generated.RunnerListView;
import net.schmurgon.gwt.request.RunnerRecordChanged;
import net.schmurgon.gwt.request.RunnerChangedHandler;

/**
 * Activity that requests and displays all {${entity.record}}
 * records.
 */
public class RunnerListActivity extends AbstractRecordListActivity<RunnerRecord> {

	private static RecordListView<RunnerRecord> defaultView;

	private static RecordListView<RunnerRecord> getDefaultView() {
		if (defaultView == null) {
			defaultView = new RunnerListView();
		}
		return defaultView;
	}

	private final ApplicationRequestFactory requests;

	/**
	 * Creates an activity that uses the default singleton view instance.
 	 */
	public RunnerListActivity(ApplicationRequestFactory requests, PlaceController placeController) {
		this(requests, getDefaultView(), placeController);
	}

	/**
   * Creates an activity that uses the given view instance.
	 */
	public RunnerListActivity(ApplicationRequestFactory requests, RecordListView<RunnerRecord> view, PlaceController placeController) {
    	super(requests, placeController, view, RunnerRecord.class);
    	this.requests = requests;
	}

	public void start(Display display, EventBus eventBus) {
    	// TODO (rjrjr) this can move to super class when event bus gets smarter
		eventBus.addHandler(RunnerRecordChanged.TYPE, new RunnerChangedHandler() {
			public void onRunnerChanged(RunnerRecordChanged event) {
				update(event.getWriteOperation(), event.getRecord());
			}
		});
		
		super.start(display, eventBus);
	}

	protected RecordListRequest<RunnerRecord> createRangeRequest(Range range) {
		return requests.runnerRequest().findRunnerEntries(range.getStart(), range.getLength());
	}

	protected void fireCountRequest(Receiver<Long> callback) {
		requests.runnerRequest().countRunners().fire(callback);
	}
}
